package com.yuntian.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuntian.dto.ProductShippingDTO;
import com.yuntian.entity.CustomerMaster;
import com.yuntian.entity.OrderData;
import com.yuntian.entity.OrderDetailData;
import com.yuntian.entity.ProductMaster;
import com.yuntian.service.CustomerService;
import com.yuntian.service.Impl.OrderdataServiceImpl;
import com.yuntian.service.ProductService2;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;



@Controller
@RequiredArgsConstructor
public class OrderdataController {
    @Autowired
    private final CustomerService customerService;
    @Autowired
    private final ProductService2 productService2;
    private final OrderdataServiceImpl orderDataService;


    /* ---------- 1. 录入画面 ---------- */
    @GetMapping("/PR10101")
    public String pr10101(Model model) {

        List<CustomerMaster> customerList = customerService.getCustomerList();
        List<ProductMaster> productList = productService2.getProductList();
        System.out.println("★ customerList size = " + customerList.size());
        System.out.println("★ productList  size = " + productList.size());
        model.addAttribute("customerList", customerList);
        model.addAttribute("productList", productList);
        return "PR10101";
    }

    @PostMapping("/saveOrder")
    public String saveOrder(
            @RequestParam("kokyaku_code") String kokyakuCode,
            @RequestParam("cartData") String cartData,
            @RequestParam("kotosi") String year,
            @RequestParam("gathu") String month,
            @RequestParam("niti") String day,
            Model model) throws Exception {

        // === 1. 客户信息 ===
        CustomerMaster customer = customerService.selectCustomerByCode(kokyakuCode);

        // === 2. 解析购物车 ===
        ObjectMapper om = new ObjectMapper();
        List<Map<String, Object>> cart = om.readValue(cartData,
                new TypeReference<List<Map<String, Object>>>() {});

        // === 3. 计算金额 ===
        long total = 0;
        for (Map<String, Object> p : cart) {
            int price = Integer.parseInt(p.get("price").toString());
            int qty   = Integer.parseInt(p.get("qty").toString());
            long amt  = (long) price * qty;
            p.put("amount", amt);
            total += amt;
        }
        long tax   = Math.round(total * 0.04);
        long grand = total + tax;

        // === 4. 生成订单号 ===
        String orderCode = String.format("%05d", new Random().nextInt(10000));

        // === 5. 组装主表实体 ===
        OrderData order = new OrderData();
        order.setT00101(orderCode);
        order.setT00105(kokyakuCode);
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy年M月d日");
        String deliveryDateStr = year + "年" + month + "月" + day + "日";
        order.setT00103(Date.valueOf(LocalDate.parse(deliveryDateStr, fmt)));
        order.setT00102(Date.valueOf(LocalDate.now()));
        order.setT00104(Date.valueOf(LocalDate.now()));
        order.setT00106("");
        order.setT00107("101");
        order.setT00108("");

        // === 6. 组装明细 ===
        List<OrderDetailData> details = new ArrayList<>();
        for (Map<String, Object> p : cart) {
            OrderDetailData d = new OrderDetailData();
            d.setT00201(orderCode);
            d.setT00202((String) p.get("productCode"));
            d.setT00203(Integer.valueOf(p.get("qty").toString()));
            d.setT00204(BigDecimal.valueOf(Double.parseDouble(p.get("price").toString())));

            details.add(d);
        }

        // === 7. 入库 ===
        orderDataService.saveOrder(order, details);

        // === 8. 给 PR10102 展示用 ===
        model.addAttribute("customer", customer);
        model.addAttribute("customerName", customer.getM00103());
        model.addAttribute("deliveryDate", deliveryDateStr);
        model.addAttribute("productList", cart);
        model.addAttribute("totalAmount", total);
        model.addAttribute("tax", tax);
        model.addAttribute("afterTaxTotal", grand);
        model.addAttribute("orderCode", orderCode);
        model.addAttribute("after3", LocalDate.now().plusDays(3).format(fmt));

        return "PR10102";
    }

    @PostMapping("/toNextPage")
    public String toNextPage(@RequestParam("kokyaku_code") String kokyakuCode,
                             @RequestParam("cartData") String cartData,
                             @RequestParam("kotosi") String year,
                             @RequestParam("gathu") String month,
                             @RequestParam("niti") String day,
                             Model model) throws JsonProcessingException {
        System.out.println(kokyakuCode);
        CustomerMaster customer = customerService.selectCustomerByCode(kokyakuCode);
        model.addAttribute("customer", customer);
        model.addAttribute("customerName", customer.getM00103());

        String deliveryDate = year + "年" + month + "月" + day + "日";
        model.addAttribute("deliveryDate", deliveryDate);

        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Object>> productList = objectMapper.readValue(
                cartData,
                new TypeReference<List<Map<String, Object>>>() {
                });
        model.addAttribute("productList", productList);


        double total = 0;
        for (Map<String, Object> product : productList) {
            int price = Integer.parseInt(product.get("price").toString());
            int qty = Integer.parseInt(product.get("qty").toString());
            product.put("code", product.get("productCode"));   // 商品编码
//            product.put("name", product.get("productName"));   // 商品名
            product.put("unit", product.get("unit") == null ? "個" : product.get("unit")); // 单位
            int amt = price * qty;

            product.put("amount", amt);   // 👈 把结果写回当前 Map
            total += amt;
        }
        double tax = total * 0.04;
        double afterTaxTotal = total + tax;
        model.addAttribute("totalAmount", total);
        model.addAttribute("tax", tax);
        model.addAttribute("afterTaxTotal", afterTaxTotal);

        String orderCode = String.format("%05d", new Random().nextInt(10000));
        model.addAttribute("orderCode", orderCode);

        LocalDate now = LocalDate.now();
        LocalDate after3 = now.plusDays(3);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        model.addAttribute("after3", after3.format(formatter));

        return "PR10102";
    }

    /**
     * 商品別出庫表 初期表示
     * 交货希望日 = 系统日期
     */
    @GetMapping("/PR10201")
    public String pr10201(@RequestParam(defaultValue = "1") int page,
                          Model model){

        LocalDate today = LocalDate.now();
        List<ProductShippingDTO> all = orderDataService.getProductShippingList(today);


        // 分页：每页10行
        int pageSize = 10;
        int total  = all.size();
        int pages  = (total + pageSize - 1) / pageSize;

        int start = (page - 1) * pageSize;
        int end   = Math.min(start + pageSize, total);
        List<ProductShippingDTO> rows = all.subList(start, end);

        model.addAttribute("rows", rows);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", pages);

        CustomerMaster customer = new CustomerMaster();
        customer.setM00101("");   // 客户代码
        customer.setM00103("");   // 客户名称
        model.addAttribute("customer", customer);

        return "PR10201";   // 你的 html 文件名
    }

    /**
     * 翻页 / 跳转
     */
    @GetMapping("/PR10201/page")
    public String pr10201Page(@RequestParam int page){
        return "redirect:/PR10201?page=" + page;
    }
}


